<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use app\service\aiAvatar\VideoAvatarService;

class VideoAvatarQuery extends Command
{
    protected function configure()
    {
        $this->setName('video_avatar:query')
            ->setDescription('查询未完成的数字人视频任务');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始查询未完成的数字人视频任务...');

        try {
            // 查询待处理的任务
            $tasks = Db::name('video_avatar_tasks')
                ->whereIn('status', [0, 1])
                ->select();

            if ($tasks->isEmpty()) {
                $output->writeln('没有未完成的任务');
                return;
            }

            $output->writeln("找到 " . count($tasks) . " 个未完成的任务");
            $videoAvatarService = new \app\service\aiAvatar\VideoAvatarService(new \app\service\TopviewApiService());
            $successCount = 0;
            $failCount = 0;

            foreach ($tasks as $task) {
                $output->writeln("正在查询任务 {$task['task_id']} (用户ID: {$task['user_id']})");
                
                try {
                    $result = $videoAvatarService->queryTask($task['task_id']);
                    $statusText = $this->getStatusText($result['status'] ?? 'unknown');
                    $output->writeln("  -> 任务 {$task['task_id']} 当前状态: {$statusText}");
                    
                    // 如果任务完成，显示结果信息
                    if (($result['status'] ?? '') === 'success') {
                        $output->writeln("  -> 视频生成成功");
                        if (!empty($result['outputVideoUrl'])) {
                            $output->writeln("  -> 视频地址: {$result['outputVideoUrl']}");
                        }
                    } elseif (($result['status'] ?? '') === 'fail') {
                        $errorMsg = $result['errorMsg'] ?? '未知错误';
                        $output->writeln("  -> 任务失败: {$errorMsg}");
                    }
                    
                    $successCount++;
                } catch (\Exception $e) {
                    $output->writeln("  -> 查询失败: {$e->getMessage()}");
                    $failCount++;
                    continue;
                }
                
                // 避免请求过于频繁
                usleep(100000); // 0.1秒
            }

            $output->writeln('==========================================');
            $output->writeln('任务查询完成');
            $output->writeln("成功查询: {$successCount} 个");
            $output->writeln("查询失败: {$failCount} 个");
            $output->writeln('==========================================');

        } catch (\Exception $e) {
            $output->writeln("<error>执行失败: {$e->getMessage()}</error>");
        }
    }

    /**
     * 获取状态文本
     */
    private function getStatusText($status)
    {
        $statusMap = [
            'init' => '待处理',
            'running' => '处理中',
            'success' => '已完成',
            'fail' => '失败',
            'unknown' => '未知状态'
        ];
        return $statusMap[$status] ?? '未知状态';
    }
} 